package com.atguigu.gmall.cart.interceptor;

import com.atguigu.gmall.cart.config.JwtProperties;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties properties;

//    private static UserInfo userInfo;
    private static final ThreadLocal<UserInfo> THREAD_LOCAL = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //System.out.println("前置拦截方法。。。。拦截前执行");
        //从cookie中获取userId 或者userKey
        String userKey = CookieUtils.getCookieValue(request, properties.getUserKey());

        //如果userKey不存在 则生成一个放入 cookie中
        if (StringUtils.isBlank(userKey)){
            userKey = UUID.randomUUID().toString();
            CookieUtils.setCookie(request,response,properties.getUserKey(),userKey,properties.getExpire());
        }

        String token = CookieUtils.getCookieValue(request, properties.getCookieName());


        Long userId = null;

        //如果toke不为空 从token中获取userId
        if (StringUtils.isNotBlank(token)){
            try {
                //解析token 获取userId
                Map<String, Object> map = JwtUtils.getInfoFromToken(token, properties.getPublicKey());
                userId = Long.valueOf(map.get("userId").toString());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("解析token出错!");
            }
        }
        //通过request传递 userId 和userKey
        //request.setAttribute("userId",userId);
        //request.setAttribute("userKey",userKey);

        //同过全局变量传递信息 会出现线程安全问题 解决不了 不使用
        //userInfo = new UserInfo(userId,userKey);

        //通过ThreadLocal传递消息
        THREAD_LOCAL.set(new UserInfo(userId,userKey));

        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //System.out.println("后置拦截方法。。。。拦截后执行");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //System.out.println("完成拦截方法。。。 在视图渲染完成后执行");
        // 一定要手动释放 ThreadLocal资源 否则可能导致内存泄漏 因为使用的是Tomcat的线程池 请求结束线程不会关闭
        THREAD_LOCAL.remove();
    }

    public static  UserInfo getUserInfo(){
        return THREAD_LOCAL.get();
    }
}
